package com.android.SummerSchoolProject;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
//import android.media.audiofx.PresetReverb;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.ArrayList;

import com.android.SummerSchoolProject.files.FilesChecking;



public class Sampler extends Activity implements FilesChecking{
	
   private static final int REVERB_ON_MENU_ID = Menu.FIRST;
   private static final int REVERB_OFF_MENU_ID = Menu.FIRST + 1;
//    PresetReverb reverb=null;
	private static final String DEBUG_TAG= "MyFirstAppLogging";
	ArrayList<Button> samplerButtons;
	ArrayList<MediaPlayer> mediaplayers;
	ArrayList<String> filepaths;
//	ArrayList<Intent> intents;
//	TextView debuginfo;
	String[] allowedformats={"3gp","mp4","m4a","aac","mp3","ogg","wav","mid"};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sampler);
        samplerButtons = new ArrayList<Button>();
        mediaplayers = new ArrayList<MediaPlayer>();
//        intents = new ArrayList<Intent>();
        filepaths = new ArrayList<String>();
//        debuginfo = (TextView) findViewById(R.id.textView1);
        samplerButtons.add((Button) findViewById(R.id.samplerbutton1));
        samplerButtons.add((Button) findViewById(R.id.samplerbutton2));
        samplerButtons.add((Button) findViewById(R.id.samplerbutton3));
        samplerButtons.add((Button) findViewById(R.id.samplerbutton4));
        int count = 0;
        for (Button b : samplerButtons) {
        	b.setTag(count);
        	count++;
        	b.setOnLongClickListener(new View.OnLongClickListener(){
            	public boolean onLongClick(View v) {
//            		intents.add(new Intent());
//                    intents.get(((Number)v.getTag()).intValue()).addCategory(Intent.CATEGORY_OPENABLE);
//                    intents.get(((Number)v.getTag()).intValue()).setType("text/csv");
//                    intents.get(((Number)v.getTag()).intValue()).setAction(Intent.ACTION_GET_CONTENT);
//                    startActivityForResult(Intent.createChooser(intents.get(((Number)v.getTag()).intValue()), "select file"),((Number)v.getTag()).intValue());
            		searchIntent(v,((Number)v.getTag()).intValue());
                    return true;
            	}
            });
        	
        }

    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(Menu.NONE, REVERB_ON_MENU_ID, 0, "Reverb ON");
        menu.add(Menu.NONE, REVERB_OFF_MENU_ID, 1, "Reverb OFF");
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case REVERB_ON_MENU_ID:
//            	reverb = new PresetReverb(10,0);
//            	reverb.setPreset(PresetReverb.PRESET_LARGEHALL);
//            	reverb.setEnabled(true);
                return true;
            case REVERB_OFF_MENU_ID:
//            	reverb.release();
                return true;
            
        }
        return super.onOptionsItemSelected(item);
    }
    
    
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
    	savedInstanceState.putStringArrayList("files", filepaths);
    	super.onSaveInstanceState(savedInstanceState);
    }
    
    
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    	filepaths = savedInstanceState.getStringArrayList("files");
        if (!filepaths.isEmpty()) {
			int cnt = 0;
			for (String path : filepaths) {
				setMediaPlayersandButtons(cnt, path);
				cnt++;
			}
		}
    }
    
    public void setMediaPlayersandButtons (int index, String filepath) {
    	if (index==mediaplayers.size()) 
			mediaplayers.add(index,	MediaPlayer.create(this, Uri.parse(filepath)));
    	else
    		mediaplayers.set(index,	MediaPlayer.create(this, Uri.parse(filepath)));
		samplerButtons.get(index).setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					if (mediaplayers.get(((Number)v.getTag()).intValue()) != null) {
						try {
							mediaplayers.get(((Number)v.getTag()).intValue()).start();
						} catch (IllegalStateException e) {
							Log.e(DEBUG_TAG, "illegal state in play", e);
						}
					}
				}
			});
		samplerButtons.get(index).setText(
				filepaths.get(index).substring(filepaths.get(index).lastIndexOf("/")+1,
						filepaths.get(index).length() - 4));
    }
    protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
    	 if (resultCode == RESULT_OK) {
             if (checkAudioFormat(data.getData().getPath())) {
            	 if (requestCode==filepaths.size())
					filepaths.add(requestCode, data.getData().getPath());
            	 else
            		filepaths.set(requestCode, data.getData().getPath());

				 setMediaPlayersandButtons (requestCode, data.getData().getPath());
		   	}
             else {
            	 Toast wrongformat = Toast.makeText(this, "wrong file format", Toast.LENGTH_SHORT);
            	 wrongformat.show();
             }
    	 }

    }
    
    @Override
    public boolean checkAudioFormat(CharSequence path){
    	for (String extension : allowedformats) {
    		if (extension.equalsIgnoreCase(path.subSequence(path.length()-3, path.length()).toString()))
    			return true;
    		if (path.subSequence(path.length()-4,path.length()).toString().equalsIgnoreCase("flac"))
    			return true;
    	}
    	return false;
    }
    protected void onStop() {
        if (!mediaplayers.isEmpty()) {
			for (MediaPlayer x : mediaplayers) {
				if (x != null) {
					x.stop();
					x.release();
				}
			}
		}
		super.onStop();
    }



    @Override
    public void searchIntent(View view, int code) {
	    Intent searchMusic = new Intent();
	    searchMusic.addCategory(Intent.CATEGORY_OPENABLE);
	    searchMusic.setType("text/csv");
	    searchMusic.setAction(Intent.ACTION_GET_CONTENT);
	    startActivityForResult(Intent.createChooser(searchMusic, "select file"),code);
    }

}
